#include "TcpSession.h"

namespace mpgl_engine{ namespace application{ namespace net {

	TcpSession::TcpSession(GlConsole* console,
		io_service* ioService, TcpSessionType sessionType,
		uint maxConnections)
			: m_console(console), m_ioService(ioService),
			m_sessionType(sessionType), m_stopRequest(false),
			Updateable(), LockableMutex()
	{

		if (maxConnections > NetworkDefines::SERVER_MAX_CLIENTS)
			m_maxConnections = NetworkDefines::SERVER_MAX_CLIENTS;
		else if (maxConnections <= 0)
			m_maxConnections = 1;
		else
			m_maxConnections = maxConnections;
		m_connections = std::vector<TcpConnection*>();

#if (TCP_SESSION_DEBUG >= 1)
		if (m_console != NULL){
			string msg = NetworkDefines::CONSOLE_MSG_PREFIX;
			msg += " TcpSession :: Constructed ";
			m_console->WriteMessage(msg);
		}
#endif
	}

	void TcpSession::Update()
	{
		//Update connections
		if ((  m_connections.size()) > 0)
		{
			while (!TryLock()){ Pause(1); }
			for (std::vector<TcpConnection*>::iterator it =
				m_connections.begin(); it < m_connections.end();
				it++)
			{
				if ( (*it) != NULL ){ (*it)->Update(); }
			}
			Unlock();
		}

	}

	/*---------------------------------------------------
	------------------------------------------------------*/

	TcpSession::~TcpSession()
	{
		//Lock
		while (!TryLock()){ Pause(1); }

		//Cleanup
		TcpConnection* tc;
		while (m_connections.size() > 0)
		{
			tc = *(m_connections.end());
			m_connections.pop_back();
			if (tc != NULL){ delete tc; }
		}

		//Unlock
		Unlock();
	}

}}}